﻿



var HH = 0, MM = 0, SS = 0;
var questioned = 0;
var QuesId = new Array();//题目Id的集合
var QuestScore = new Array();//分数集合
var questType = new Array();//题型集合
var checkQues = [];//已经答题的集合
var activeQuestion = 0;//当前操作的答题号
var itemList = ["A", "B", "C", "D", "E", "F"];
var questions=[];
ExamStart();

//获取题目的数据
function getQuestionData(id) {
    $.ajax({
        async: false,
        url: "/Main/GetQuestionByStu",  // 跨域URL
        type: "post",
        dataType: "json",
        data: {
            id: id
        },
        success: function (json) { //客户端jquery预先定义好的callback函数，成功获取跨域服务器上的json数据后，会动态执行这个callback函数
            questions = json;
            for (let i in questions) {
                if (Object.prototype.hasOwnProperty.call(questions, i)) {
                    QuesId.push(questions[i].QuestionId);
                    questType.push(questions[i].QuestionType);
                    QuestScore.push(questions[i].QuestionScore);
                    const check = {
                        id: parseInt(i),
                        item: null,
                        type: questions[i].QuestionType,
                        answer: ""
                    };
                    checkQues.push(check);
                }
            }
        }
    });
};

$(function () {
    $(".middle-top-left").width($(".middle-top").width() - $(".middle-top-right").width());
    $(".progress-left").width($(".middle-top-left").width() - 200);
    Progress();
    //answerCard();
    //答题卡的切换
    $("#openCard").click(function () {
        $("#closeCard").show();
        $(this).hide();
        $("#answerCard").slideDown();
    });
    $("#closeCard").click(function () {
        $(this).hide();
        $("#openCard").show();
        $("#answerCard").slideUp();
    });
    //收藏按钮的切换
    $("#unHeart").click(function () {
        $(this).hide();
        $("#heart").show();
    });
    $("#heart").click(function () {
        $(this).hide();
        $("#unHeart").show();
    });
    //下一题
    var countTimes = 0;//计数器
    $("#nextQuestion").click(function () {
        if ((activeQuestion + 1) < questions.length - 1) {
            showQuestion(activeQuestion + 1);
            $("#preQuestion").removeAttr("disabled");
            countTimes = 0;
        } else {
            if (countTimes>= 1) {  //当最后一题时，再点一下以触发进度条
                $("#nextQuestion").attr("disabled", "disabled");
                Progress();
                countTimes++;
            } else {
                showQuestion(activeQuestion + 1);
                countTimes ++;
            }
            $("#preQuestion").removeAttr("disabled");
        }
        //showQuestion(activeQuestion);
    });
    //上一题
    $("#preQuestion").click(function () {
        if ((activeQuestion - 1) > 0) {
            showQuestion(activeQuestion - 1);
            $("#nextQuestion").removeAttr("disabled");
            countTimes = 0;
        } else {
            showQuestion(activeQuestion - 1);
            $("#nextQuestion").removeAttr("disabled");
            $("#preQuestion").attr("disabled", "disabled");
            countTimes = 0;
        }
    });
});
//设置进度条 
function Progress() {
    var countLength = 0;
    for (var o = 0; o < checkQues.length; o++) {
         //为空时不触发进度条
         if (checkQues[o].answer !== "") {
             countLength++;
         }
    }
    //var hasCompleteOrNot = $(".clickQue").length;
    //var prog = hasCompleteOrNot / questions.length;
    var prog = countLength / questions.length;
    //var prog = ($(".active_question_id").length) / questions.length;
    var pro = $(".progress").parent().width() * prog;
    $(".progres").text((prog * 100).toString().substr(0, 5) + "%");
    $(".progress").animate({
        width: pro,
        opacity: 0.5
    }, 1000);
}
//答题卡
function answerCard() {
    $(".question_sum").text(questions.length);
    for (var i = 0; i < questions.length; i++) {
        var questionId = `<li id='ques${i}' onclick='saveQuestionState(${i})' class='questionId'>${i + 1}</li>`;
        $("#answerCard ul").append(questionId);
    }
}
//展示试卷信息
function showQuestion(id) {
    
    $(".questioned").text(id + 1);
    questioned = (id + 1) / questions.length;
    if (activeQuestion != undefined) {
        $(`#ques${activeQuestion}`).removeClass("question_id").addClass("active_question_id");//类active_question_id表示查看过的题目
    }
    activeQuestion = id;//当前题号，从0开始
    $(".question").find(".question_info").remove();
    var question = questions[id];
    $(".question_title").html(`<strong>第${id + 1}题,&nbsp;</strong>${question.QuestionTitle}`);
    //题型判断
    var item;
    if (question.QuestionType === 1) {
        $("#questionType").text("[单选题]");
        var items = question.QuestionItems.split("::"); //分割选项
        item = "";
        for (var n1 = 0; n1 < items.length - 1; n1++) {
            //data-type='1'选择题
            item = `<li class='question_info' data-type='1' onclick='clickTrim(this)' id='item${n1}'> 
                        <input type='radio' name='item' value='${items[n1]}'>${itemList[n1]}.${items[n1]}
                        </li>`;
            $(".question").append(item);
        }
    } else if (question.QuestionType === 2) {
        $("#questionType").text("[判断题]");
        item = "";
        item = "<li class='question_info' onclick='clickTrim(this)' data-type='2' id='item1'>" +
            "<input type='radio' name='item' value='1' >正确</li>" +
            "<li class='question_info' onclick='clickTrim(this)'data-type='2' id='item0'>" +
            "<input type='radio' name='item' value='0' >错误</li>";
        $(".question").append(item);
    }
    else if (question.QuestionType === 3) {
        $("#questionType").text("[填空题]");
        item = "";
        item = "<div class='question_info box' style='padding-left:0' id='itemBlank'>"
            + "<textarea id='blankValue'  style='min-width:100%;'  placeholder='请输入,多个填空请用英文半角逗号隔开' onfocus='clickBlankTrim()' onblur='clickBlankTrim()' class='layui-textarea'></textarea>"
            + "</div>";
        $(".question").append(item);
    }

    $(".question").attr("id", "question" + id);
    $(`#ques${id}`).removeClass("active_question_id").addClass("question_id");
    //已经做过该题，显示该题的题目的时候显示选中的答案
    for (var m = 0; m < checkQues.length; m++) {
        if (checkQues[m].id === id) {
            if (checkQues[m].type===3) { //判断题另外处理
                $(`#${checkQues[m].item}`).val(checkQues[m].answer);
            } else {
                $(`#${checkQues[m].item}`).find("input").prop("checked", "checked");
                $(`#${checkQues[m].item}`).addClass("clickTrim");
            }
           $(`#ques${activeQuestion}`).removeClass("question_id").addClass("clickQue");
        }
    }
    Progress();
    //console.log(checkQues);
}
//保存试题状态(是否已答，是否查看过)
function saveQuestionState(clickId) {
    showQuestion(clickId);
}
//选中考题
var Question;
//应用于选择题 判断题
function clickTrim(source) {
    var id = source.id;
    $(`#${id}`).find("input").prop("checked", "checked");
    $(`#${id}`).addClass("clickTrim");//加上类clickTrim表示选中状态
    $(`#ques${activeQuestion}`).removeClass("question_id").addClass("clickQue");//类clickQue表示该题已答，类question_id表示当前选中的题目
    for (let i = 0; i < checkQues.length; i++) {
        //已经答过的题修改答案，checkQues[i].id题号不修改
        if (checkQues[i].id === activeQuestion && checkQues[i].item !== id) {
            checkQues[i].item = id;
            checkQues[i].answer = $(`#${id}`).find("input[name='item']:checked").val();//获取当前试题的选项值
        }
    }
    //对该题之前选中的选项进行删除
    $(".question_info").each(function () {
        const otherId = $(this).attr("id");
        if (otherId !== id) {
            $(`#${otherId}`).find("input").prop("checked", false);
            $(`#${otherId}`).removeClass("clickTrim");
        }
    });
    Question = activeQuestion;
}
//应用于填空题
function clickBlankTrim() {
    const id = "blankValue";
    //类clickQue表示该题已答，类question_id表示当前选中的题目
    $(`#ques${activeQuestion}`).removeClass("question_id").addClass("clickQue");
    for (let i = 0; i < checkQues.length; i++) {
        //已经答过的题修改答案，checkQues[i].id题号不修改
        if (checkQues[i].id === activeQuestion) {
            checkQues[i].item = id;
            checkQues[i].answer = $(`#${id}`).val();//获取当前试题的选项值
        }
    }
    Question = activeQuestion;
}
//开考提示
function ExamStart() {
// ReSharper disable once UseOfImplicitGlobalInFunctionScope
    layui.use("layer", function () {
        layer.open({
            type: 1
            , title: false
            , closeBtn: false
            , area: ["500px", "auto"]
            , shade: 0.8
            , id: "LAY_1" //设定一个id，防止重复弹出
            , btn: ["开始测试"]
            , btnAlign: "c"
            , moveType: 0 //拖拽模式，0或者1
            , content: ' <div class="row" style="width: 420px;padding: 20px;  line-height: 22px; margin-left:30px; margin-top:10px;font-weight: 300;">'
                + '<div style="font-size:18pt; text-align:center">开考说明</div><hr>'
                + '<div class="col-sm-12">'
                + '<div class="input-group">'
                + '<span class="input-group-addon" style="background:white;border:none"> 考试名称：</span>'
                + '<span id="ExamName"></span>'
                + "</div>"
                + "</div>"
                + '<div class="col-sm-12" style="margin-top: 10px">'
                + '<div class="input-group">'
                + '<span class="input-group-addon" style="background:white;border:none">出&ensp;卷&ensp;人：</span>'
                + '<span id="Creator"></span>'
                + "</div>"
                + "</div>"
                + '<div class="col-sm-12" style="margin-top: 10px">'
                + '<div class="input-group">'
                + '<span class="input-group-addon" style="background:white;border:none">限&emsp;&emsp;时：</span>'
                + '<span id="OnTime"></span>'
                + "</div>"
                + "</div>"
                + '<div class="col-sm-12" style="margin-top:10px;">'
                + '<div class="input-group">'
                + '<span class="input-group-addon" style="background:white;border:none">考试规则：</span>'
                + "<span>允许在作答期间，返回修改答案</span>"
                + "</div> "
                + "</div> "
                + '<div class="col-sm-12" style="margin-top: 10px">'
                + '<div class="input-group">'
                + "<span>如果考试异常中断，请退出并及时按相同步骤进入，继续考试</span>"
                + "</div>"
                + "</div>"
                + "</div>"
            , btn1: function (index) {
                if (OnTime > 0) {
                    LimitTimeCount();
                } else {
                    $("#limitTime").html("不限时");
                }
                
                getQuestionData(TestPaperTbId);
                showQuestion(0);
                answerCard();
                if (questions.length <= 1) {
                    $("#nextQuestion").attr("disabled", "disabled");
                }
                layer.close(index);
            }
        });
        $("#ExamName").text(ExamName);
        $("#Creator").text(Creator);
        if (OnTime === "0") {
            $("#OnTime").text("不限时");
        } else {
            $("#OnTime").text(OnTime + "分钟");
        }
    });
}
//限时
function LimitTimeCount() {
    var curTime = new Date();
    var addHour = new Date(curTime.setMinutes(curTime.getMinutes() + parseInt(OnTime)));
    layui.use('util', function () {
        var util = layui.util;
        var endTime = addHour
            , serverTime = new Date().getTime();
        util.countdown(endTime, serverTime, function (date, serverTime, timer) {
            var str = date[0] + '天' + date[1] + '时' + date[2] + '分' + date[3] + '秒';
            if ( date[2] <= 1 &&date[0] === 0 && date[1] === 0) {
                $('#limitTime').attr("style", "color:orange");
            }
            layui.$('#limitTime').html(str);
            if (date[3] === 0&&date[2] === 0 && date[1] === 0 && date[0] === 0) {
                StopExam();
            }
        });
    });
}
//考试暂停
var interval;
function StopExam() {
    layui.use('layer', function () {
        var index=layer.open({
            type: 1
            , title: false
            , closeBtn: false
            , area: ["60%", "80%"]
            , shade: 0.8
            , id: "pauseExam" //设定一个id，防止重复弹出
            , btn: ["确认"]
            , content: `<div class="row" style="width:100%;font-weight: 300;">
                            <hr>
                            <p style="font-size:28pt; text-align:center">考试结束</p>
                            <hr>
                            <br/>
                            <br/>
                            <br/>
                            <br/>
                            <p id="autoTime" style="text-align:center"></p>
                            <p style="text-align:center">请勿关闭页面，否则成绩无效</p>
                        </div>`
            , btn1: function (index) {
                layer.close(index);
            }
        });
        var time = 5;
        $("#autoTime").text(time + "s后自动提交");
        interval = setInterval(function () {
            time--;
            $("#autoTime").text(time+"s后自动提交");
            if (time === 0) {
                DisposeQuest();
                clearInterval(interval);
                layer.close(index);
            }
        }, 1000);
    });
}
//提交试卷
function SubmitAnswers() {
    var countLength = 0;
    var str = "";
    for (let o = 0; o < checkQues.length; o++) {
        //为空时不触发进度条
        if (checkQues[o].answer !== "") {
            countLength++;
        }
    }
    if (countLength !== questions.length)
        str = `还有${questions.length - countLength}道题未完成确认提交?`;
    else
        str = "所有题目已做完，确认提交?";
    layer.open({
        id: 1,
        type: 1,
        title: "提交试卷",
        area: ["20%", "auto"],
        content: ` <div class="row" style="width: 95%;  margin-left:7px;">
                        <div class="col-sm-12">
                            <p></p>
                            <p>${str}</p>
                        </div>
                    </div>`,
        btn: ["确定", "取消"],
        btn1: function (index) {
            DisposeQuest();
        },
        btn2: function (index) {
            layer.close(index);
        }
    });

}
//整理试题
function DisposeQuest() {
    
    //排序
    for (let x in checkQues) {
        for (let y in checkQues) {
            if (checkQues[x].id < checkQues[y].id) {
                const z = checkQues[x];
                checkQues[x] = checkQues[y];
                checkQues[y] = z;
            }
        }
    }
    //重排序赋值
    var arr = new Array(QuesId.length);
    var j = 0;
    for (let i = 0; i < arr.length; i++) {
        if (j < checkQues.length) {
            if (checkQues[j].id === i) {
                arr[i] = checkQues[j].answer;
                j++;
                continue;
            }
        }
        arr[i] = "";
    }
    console.log(arr);
    var loading = layer.msg('提交中',
        {
            icon: 16,
            time: 5000,
            shade: 0.1
        });

    $.ajax({
        type: "POST",
        url: "/AnswerInfoTb/Examination",
        data: {
            testPaperTbId: TestPaperTbId,
            questionTbId: QuesId,
            answer: arr,
            type: questType,
            score: QuestScore
        },
        dataType: "text",

        success: function (data) {
            layer.msg("保存成功，请等待考试结束后，查看成绩！");
            layer.close(loading);
            setTimeout(goto, 2000);
            function goto() {
                history.go(-1);
            }
        }
    });
}
//实现倒计时
//var timer = setInterval(function () {
//    if (timeState) {
//        if (HH == 24) HH = 0;
//        var str = "";
//        if (++SS == 60) {
//            if (++MM == 60) {
//                HH++;
//                MM = 0;
//            }
//            SS = 0;
//        }
//        str += HH < 10 ? "0" + HH : HH;
//        str += ":";
//        str += MM < 10 ? "0" + MM : MM;
//        str += ":";
//        str += SS < 10 ? "0" + SS : SS;
//        $(".time").text(str);
//    } else {
//        $(".time").text(str);
//    }
//}, 1000);